//
//  SelectWorkerViewController.m
//  MagictoLane
//
//  Created by 锋 on 2017/12/21.
//  Copyright © 2017年 HUAYU. All rights reserved.
//

#import "SelectWorkerViewController.h"
#import "SelectWorkerTableViewCell.h"
#import "WorkerDetailViewController.h"
#import "WorkerMessagesViewController.h"
#import "SelectWorkerModel.h"

@interface SelectWorkerViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *selectWorkerTableView;
@property (nonatomic, strong) UILabel *lineLabel;
@property (nonatomic, assign) NSInteger leftPage;
@property (nonatomic, assign) NSInteger rightPage;
@property (nonatomic, strong) NSMutableArray *workerListArr;
@property (nonatomic, strong) NSMutableArray *workerApplyListArr;
@property (nonatomic, assign) NSInteger chooseType;
@property (nonatomic, assign) NSInteger leftWhichWorker;
@property (nonatomic, assign) NSInteger rightWhichWorker;
@property (nonatomic, strong) NSMutableArray *leftIsSelectArr;
@property (nonatomic, strong) NSMutableArray *rightIsSelectArr;
@end

@implementation SelectWorkerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _chooseType = 0;
    _leftPage = 0;
    _rightPage = 0;
    _workerListArr = @[].mutableCopy;
    _workerApplyListArr = @[].mutableCopy;
    _leftIsSelectArr = @[].mutableCopy;
    _rightIsSelectArr = @[].mutableCopy;
    [self setupUI];
    [self setupSelectWorkerTableView];
    [self requestApplyWorkerList];
    [self requestWorkerList];
    // Do any additional setup after loading the view.
}

- (void)setupUI {
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithTitle:@"确认" style:UIBarButtonItemStylePlain target:self action:@selector(onClickEnsureBtn)];
    [rightBtn setTintColor:[UIColor whiteColor]];
    [rightBtn setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15], UITextAttributeFont,nil] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = rightBtn;
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"选择工人";
    self.view.backgroundColor = RGB(242, 242, 242);
    
    UIButton *topLeftBtn = [ZCControl createButtonWithFrame:CGRectMake(0, 0, SCREEN_WIDTH / 2, 40) ImageName:nil Target:self Action:@selector(onClickLeftBtn:) Title:@"报名" Font:15];
    UIButton *topRightBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH / 2, 0, SCREEN_WIDTH / 2, 40) ImageName:nil Target:self Action:@selector(onClickRightBtn:) Title:@"推荐" Font:15];
    [topLeftBtn setTitleColor:UIColorHexValue(0x4D4D4D) forState:UIControlStateNormal];
    [topRightBtn setTitleColor:UIColorHexValue(0x4D4D4D) forState:UIControlStateNormal];
    topLeftBtn.backgroundColor = [UIColor whiteColor];
    topRightBtn.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:topLeftBtn];
    [self.view addSubview:topRightBtn];
    _lineLabel = [ZCControl createLabelWithFrame:CGRectMake(0, 36, 43, 4) Font:15 Text:nil Color:nil];
    _lineLabel.backgroundColor = RGB(235, 102, 93);
    _lineLabel.center = CGPointMake(topLeftBtn.center.x, 38);
    _lineLabel.layer.cornerRadius = 2;
    _lineLabel.layer.masksToBounds = YES;
    [self.view addSubview:_lineLabel];
}
- (void)setupSelectWorkerTableView {
    _selectWorkerTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 40, SCREEN_WIDTH, SCREEN_HEIGHT - STA_NAV_HEIGHT - SCREER_HeiX - 40) style:UITableViewStyleGrouped];
    _selectWorkerTableView.delegate = self;
    _selectWorkerTableView.dataSource = self;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.000001)];
    view.backgroundColor = [UIColor whiteColor];
    _selectWorkerTableView.tableHeaderView = view;
    _selectWorkerTableView.tableFooterView = view;
    self.selectWorkerTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewHeaderData)];
    self.selectWorkerTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreFootData)];
    self.selectWorkerTableView.mj_footer.automaticallyHidden = YES;
    self.selectWorkerTableView.estimatedRowHeight = 0;
    self.selectWorkerTableView.estimatedSectionHeaderHeight = 0;
    self.selectWorkerTableView.estimatedSectionFooterHeight = 0;
    _selectWorkerTableView.backgroundColor = RGB(242, 242, 242);
    if (@available(iOS 11.0, *)) {
        _selectWorkerTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    _selectWorkerTableView.estimatedRowHeight = 0;
    _selectWorkerTableView.estimatedSectionHeaderHeight = 0;
    _selectWorkerTableView.estimatedSectionFooterHeight = 0;
    [self.view addSubview:_selectWorkerTableView];
}

- (void)loadNewHeaderData {
    if (_chooseType == 0) {
        _leftPage = 0;
        [self requestApplyWorkerList];
    } else {
        _rightPage = 0;
        [self requestWorkerList];
    }
}

- (void)loadMoreFootData {
    if (_chooseType == 0) {
        _leftPage++;
        [self requestApplyWorkerList];
    } else {
        _rightPage++;
        [self requestWorkerList];
    }
}

//系统推荐
- (void)requestWorkerList {
    WEAKSELF;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HYBaseHandler requestWorkerListParmers:@{@"projectSpotId" : _spotsId, @"page" : [NSString stringWithFormat:@"%ld", (long)_rightPage]} Success:^(id obj)
     {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         [weakSelf.selectWorkerTableView.mj_header endRefreshing];
         [weakSelf.selectWorkerTableView.mj_footer endRefreshing];
         if ([obj server_Getcodecheck])
         {
             NSLog(@"%@", obj);
             NSArray *tempArray = [SelectWorkerModel mj_objectArrayWithKeyValuesArray:obj[@"data"][@"content"]];
             if (weakSelf.rightPage == 0)
             {
                 [weakSelf.workerListArr removeAllObjects];
             }
             [weakSelf.workerListArr addObjectsFromArray:tempArray];
             for (int i = 0; i < weakSelf.workerListArr.count; i++) {
                 [weakSelf.rightIsSelectArr addObject:@(NO)];
             }
             [_selectWorkerTableView reloadData];
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
     } failed:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         [weakSelf.selectWorkerTableView.mj_header endRefreshing];
         [weakSelf.selectWorkerTableView.mj_footer endRefreshing];
     }];
}

//报名工人列表
- (void)requestApplyWorkerList {
    WEAKSELF;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HYBaseHandler requestApplyWorkerListParmers:@{@"projectSpotId" : _spotsId, @"page" : [NSString stringWithFormat:@"%ld", (long)_leftPage]} Success:^(id obj)
     {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         [weakSelf.selectWorkerTableView.mj_header endRefreshing];
         [weakSelf.selectWorkerTableView.mj_footer endRefreshing];
         if ([obj server_Getcodecheck])
         {
             NSLog(@"%@", obj);
             NSArray *tempArray = [SelectWorkerModel mj_objectArrayWithKeyValuesArray:obj[@"data"][@"content"]];
             if (weakSelf.leftPage == 0)
             {
                 [weakSelf.workerApplyListArr removeAllObjects];
             }
             [weakSelf.workerApplyListArr addObjectsFromArray:tempArray];
             for (int i = 0; i < weakSelf.workerApplyListArr.count; i++) {
                 [weakSelf.leftIsSelectArr addObject:@(NO)];
             }
             [_selectWorkerTableView reloadData];
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
     } failed:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         [weakSelf.selectWorkerTableView.mj_header endRefreshing];
         [weakSelf.selectWorkerTableView.mj_footer endRefreshing];
     }];
}

- (void)onClickLeftBtn:(UIButton *)sender {
    _chooseType = 0;
    [Utilities underLineSlideAnimation:_lineLabel withAlignView:sender andAnimationView:nil];
    [_selectWorkerTableView reloadData];
}

- (void)onClickRightBtn:(UIButton *)sender {
    _chooseType = 1;
    [Utilities underLineSlideAnimation:_lineLabel withAlignView:sender andAnimationView:nil];
    [_selectWorkerTableView reloadData];
}

// MARK:tableview的方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_chooseType == 0) {
        return _workerApplyListArr.count;
    } else {
        return _workerListArr.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 90;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 5;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.000001;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SelectWorkerTableViewCell *cell = [[NSBundle mainBundle] loadNibNamed:@"SelectWorkerTableViewCell" owner:self options:nil].lastObject;
    BOOL isSelect;
//    cell.statusBtn.tag = indexPath.row;
//    [cell.statusBtn addTarget:self action:@selector(onClickStatusBtn:) forControlEvents:UIControlEventTouchUpInside];
    cell.workerIcon.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onClickWorkerIcon:)];
    cell.workerIcon.tag = indexPath.row;
    [cell.workerIcon addGestureRecognizer:tap];
    SelectWorkerModel *model;
    if (_chooseType == 0) {
        isSelect = [_leftIsSelectArr[indexPath.row] boolValue];
        model = _workerApplyListArr[indexPath.row];
    } else {
        isSelect = [_rightIsSelectArr[indexPath.row] boolValue];
        model = _workerListArr[indexPath.row];
    }
    cell.statusBtn.selected = isSelect;
    [cell.workerIcon sd_setImageWithURL:[NSURL URLWithString:model.user.headImg] placeholderImage:nil];
    cell.nameLabel.text = model.linkman;
    cell.referencePriceLabel.text = [NSString stringWithFormat:@"参考价:%@元/小时", model.wageSystem];
    cell.quoteLabel.text = [NSString stringWithFormat:@"报价:%@元/小时", model.wage];
    [cell.projectNumberBtn setTitle:model.user.finishCount forState:UIControlStateNormal];
    [cell.gradeNumberBtn setTitle:model.user.grade forState:UIControlStateNormal];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SelectWorkerTableViewCell *cell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row inSection:0]];
    if (_chooseType == 0) {
        _leftWhichWorker = indexPath.row;
        _leftIsSelectArr[indexPath.row] = @(YES);
        for (int i = 0; i < _workerApplyListArr.count; i++) {
            if (i != indexPath.row) {
                SelectWorkerTableViewCell *cell = [_selectWorkerTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
                cell.statusBtn.selected = NO;
                _leftIsSelectArr[i] = @(NO);
            }
        }
        _rightWhichWorker = -1;
        for (int i = 0; i < _workerListArr.count; i++) {
            _workerListArr[i] = @(NO);
        }
    } else {
        _rightWhichWorker = indexPath.row;
        _rightIsSelectArr[indexPath.row] = @(YES);
        for (int i = 0; i < _workerListArr.count; i++) {
            if (i != indexPath.row) {
                SelectWorkerTableViewCell *cell = [_selectWorkerTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
                cell.statusBtn.selected = NO;
                _rightIsSelectArr[i] = @(NO);
            }
        }
        _leftWhichWorker = -1;
        for (int i = 0; i < _workerApplyListArr.count; i++) {
            _workerApplyListArr[i] = @(NO);
        }
    }
    cell.statusBtn.selected = YES;
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)onClickWorkerIcon:(UITapGestureRecognizer *)tap {
    if (_chooseType == 0) {
        WorkerMessagesViewController *messageVC = [[WorkerMessagesViewController alloc] init];
        SelectWorkerModel *model = _workerApplyListArr[tap.view.tag];
        messageVC.ID = model.ID;
        messageVC.targetId = model.user.ID;
        [self.navigationController pushViewController:messageVC animated:YES];
    } else {
        WorkerMessagesViewController *messageVC = [[WorkerMessagesViewController alloc] init];
        SelectWorkerModel *model = _workerListArr[tap.view.tag];
        messageVC.ID = model.ID;
        messageVC.targetId = model.user.ID;
        [self.navigationController pushViewController:messageVC animated:YES];
    }
}

- (void)onClickEnsureBtn {
    WEAKSELF;
    if (_leftWhichWorker >= 0 || _rightWhichWorker >= 0) {
        NSDictionary *dic;
        if (_chooseType == 0) {
            if (_workerApplyListArr.count > 0) {
                SelectWorkerModel *model = _workerApplyListArr[_leftWhichWorker];
                dic = @{@"id" : _spotsId, @"workerId" : model.ID};
            } else {
                [LTools showMBProgressWithText:@"请选择工人" addToView:weakSelf.view];
                return;
            }
        } else {
            if (_workerListArr.count > 0) {
                SelectWorkerModel *model = _workerListArr[_rightWhichWorker];
                dic = @{@"id" : _spotsId, @"workerId" : model.ID};
            } else {
                [LTools showMBProgressWithText:@"请选择工人" addToView:weakSelf.view];
                return;
            }
        }
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [HYBaseHandler requestWorkerEnsureParmers:dic Success:^(id obj)
         {
             [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
             if ([obj server_Getcodecheck])
             {
                 NSLog(@"%@", obj);
                 [LTools showMBProgressWithText:@"提交成功" addToView:weakSelf.view];
                 [self.navigationController popViewControllerAnimated:YES];
             }
             else
             {
                 [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
             }
         } failed:^(NSError *error) {
             [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
             
         }];
    } else {
        [LTools showMBProgressWithText:@"请选择工人" addToView:weakSelf.view];
    }
}

- (void)onClickStatusBtn:(UIButton *)sender {
//    sender.selected = !sender.selected;
//    if (_chooseType == 0) {
//        if (sender.selected) {
//            _leftWhichWorker = sender.tag;
//            for (int i = 0; i < _workerApplyListArr.count; i++) {
//                if (i != sender.tag) {
//                    SelectWorkerTableViewCell *cell = [_selectWorkerTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
//                    cell.statusBtn.selected = NO;
//                }
//            }
//        } else {
//            _leftWhichWorker = -1;
//        }
//    } else {
//        if (sender.selected) {
//            _rightWhichWorker = sender.tag;
//            for (int i = 0; i < _workerListArr.count; i++) {
//                if (i != sender.tag) {
//                    SelectWorkerTableViewCell *cell = [_selectWorkerTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
//                    cell.statusBtn.selected = NO;
//                }
//            }
//        } else {
//            _rightWhichWorker = -1;
//        }
//    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
